package com.caigou.modules.info.ui.myself

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.info.R
import com.caigou.modules.info.adapter.MyInfoItemAdapter
import com.caigou.modules.info.bean.InfoBean
import com.caigou.modules.info.bean.InfoItemBean
import com.caigou.modules.info.databinding.FragmentMyInfoBinding
import com.caigou.modules.info.viewmodel.MyInfoViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/11/20
 */
@AndroidEntryPoint
class MyInfoFragment : BaseFragment() {

    private var _binding: FragmentMyInfoBinding? = null
    private val binding get() = _binding!!

    private val myInfoViewModel: MyInfoViewModel by viewModels()
    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var checkStatus = 0

    private val items: MutableList<InfoItemBean> by lazy {
        mutableListOf()
    }

    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireActivity())
    }

    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireActivity())
    }

    private val mAdapter: MyInfoItemAdapter by lazy {
        MyInfoItemAdapter(mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentMyInfoBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.myInfoSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                mAdapter.loadMoreModule.isEnableLoadMore = false
                page = 1
                myInfoViewModel.getMyInfoList(page, limit, AppBackgroundInfo.instance.userBean!!.userId, checkStatus)
            }
        }

        mAdapter.run {
            loadMoreModule.setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                myInfoViewModel.getMyInfoList(page, limit, AppBackgroundInfo.instance.userBean!!.userId, checkStatus)
            }
            loadMoreModule.isAutoLoadMore = true
            loadMoreModule.isEnableLoadMoreIfNotFullPage = false
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build(RouterPath.Article.PAGE_ARTICLE)
                .withObject(AppConstants.ARTICLE_ITEM_BEAN, items[position])
                .navigation()
        }

        binding.myInfoRecyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }

        binding.myInfoRgSelector.setOnCheckedChangeListener { group, checkedId ->
            checkStatus = when (group.checkedRadioButtonId) {
                binding.myInfoBtnAll.id -> 0
                binding.myInfoBtnPass.id -> 1
                binding.myInfoBtnFailed.id -> 2
                binding.myInfoBtnReview.id -> 3
                else -> 0
            }
            page = 1
            totalPage = 0
            myInfoViewModel.getMyInfoList(page, limit, AppBackgroundInfo.instance.userBean!!.userId, checkStatus)
        }
    }

    override fun lazyLoad() {
        myInfoViewModel.getMyInfoList(page, limit, AppBackgroundInfo.instance.userBean!!.userId, checkStatus)
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        observe(myInfoViewModel.myInfoListLiveData, ::handleGetMyInfoList)
    }

    private fun handleGetMyInfoList(result: Resource<InfoBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.myInfoSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取我的资料信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.myInfoSwipeRefreshLayout.isRefreshing = false
                mAdapter.loadMoreModule.isEnableLoadMore = true
                if (result.data == null) {
                    binding.myInfoDetailLlEmpty.visibility = View.VISIBLE
                    binding.myInfoRecyclerView.visibility = View.GONE
                    return
                }

                if (result.data!!.list.isNullOrEmpty()) {
                    binding.myInfoDetailLlEmpty.visibility = View.VISIBLE
                    binding.myInfoRecyclerView.visibility = View.GONE
                } else {
                    binding.myInfoDetailLlEmpty.visibility = View.GONE
                    binding.myInfoRecyclerView.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    items.clear()
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }
                items.addAll(result.data!!.list)

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }
}